package com.pangu.util;

import com.pangu.bean.ModuleConfig;
import com.pangu.service.ActionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 模块的配置文件的解析器
 * <p/>
 * 配置示例如下：
 * <p/>
 * {
 * "data": [
 * {
 * "key": "xxx_module",
 * "classname": "cn.pdl.xxx.XXXModule",
 * "delay": false,
 * "depends": [
 * "a_module",
 * "b_module"
 * ]
 * }
 * ]
 * }
 * <p/>
 * <p/>
 * Created by cuijianhui_91 on 2015/7/20.
 */
public class ModuleConfigJsonParser {

    private static final String TAG = ModuleConfigJsonParser.class.getSimpleName();

    private ArrayList<ModuleConfig> moduleConfigList;

    /**
     * 解析json
     *
     * @param jsonObj
     * @throws ActionException
     */
    public void parserJson(JSONObject jsonObj) throws ActionException {
        try {
            JSONArray moduleArray = jsonObj.optJSONArray("data");
            if (moduleArray != null) {
                moduleConfigList = parseModuleInfoList(moduleArray);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new ActionException(ActionException.OPERATE_ERROR, "数据解析异常");
        }
    }

    private ArrayList<ModuleConfig> parseModuleInfoList(JSONArray jsonArray) throws JSONException {
        ArrayList<ModuleConfig> moduleConfigList = new ArrayList<ModuleConfig>();
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject moduleInfo = jsonArray.optJSONObject(i);
                if (moduleInfo != null) {
                    String key = moduleInfo.optString("key");
                    String classname = moduleInfo.optString("classname");
                    if (StringUtil.isEmptyString(key) || StringUtil.isEmptyString(classname)) {
                        continue;
                    }
                    ModuleConfig moduleConfig = new ModuleConfig(key, classname);

                    boolean delay = moduleInfo.optBoolean("delay");
                    moduleConfig.setDelay(delay);

                    JSONArray dependsArray = moduleInfo.optJSONArray("depends");
                    if (dependsArray != null) {
                        for (int j = 0; j < dependsArray.length(); j++) {
                            String depend = (String) dependsArray.opt(j);
                            if (!StringUtil.isEmptyString(depend)) {
                                moduleConfig.addDependModule(depend);
                            }
                        }
                    }

                    moduleConfigList.add(moduleConfig);
                }
            }
        }

        return moduleConfigList;
    }

    public ArrayList<ModuleConfig> getModuleConfigList() {
        return moduleConfigList;
    }
}
